import Koa from 'koa';
import Router from 'koa-router';
import cors from 'koa2-cors';
import bodyparser from 'koa-bodyparser';
import {DataTypes,Op,Sequelize} from 'sequelize';

let koa=new Koa();
let router=new Router();

let sequelize=new Sequelize('test','sa','123456',{
    host:'localhost',
    dialect:'mssql'
});

let Blogs=sequelize.define('Blogs',{
    title:{type:DataTypes.STRING},
    content:{type:DataTypes.STRING},
    flag:{type:DataTypes.STRING}
});

await Blogs.sync();

router.post('/blogs',async(ctx)=>{
    let obj=ctx.request.body;
    let row=await Blogs.create(obj);

    ctx.body={
        code:1000,
        data:row,
        msg:'创建成功'
    }
});

router.delete('/blogs/:id',async (ctx)=>{
    let id=ctx.params.id || 0;
    let row=await Blogs.findByPk(id);
    if(row){
        Blogs.destroy({
            where:{
                id:id
            }
        });
        ctx.body={
            code:1000,
            data:[],
            msg:"删除成功"
        }
    }else{
        ctx.body={
            code:3000,
            data:[],
            msg:'没找到'
        }
    }
});

router.put('/blogs/:id',async(ctx)=>{
    let obj=ctx.request.body;
    let id=ctx.params.id || 0;
    let row=await Blogs.findByPk(id);
    if(row){
        let list=await Blogs.update(obj,{
            where:{
                id:id
            }
        });
        ctx.body={
            code:1000,
            data:list,
            msg:'修改成功'
        }
    }
});

router.get('/blogs/:id?',async(ctx)=>{
    let id=ctx.params.id;
    let list=await Blogs.findByPk(id);
    if(list){
        let row=await Blogs({
            where:{
                id:id
            }
        });
        ctx.body={
            code:1000,
            data:row[0],
            msg:'根据ID查找数据成功'
        }
    }else{
        let row=await Blogs.findAll();
        ctx.body={
            code:1000,
            data:row,
            msg:'查找所有数据成果'
        }
    }
});

router.get('/blogs',async (ctx)=>{
    let keyword=ctx.request.query.keyword|| '';
    keyword=keyword.trim();
    if(keyword){
        let row=await Blogs.findAll({
            where:{
                [Op.or]:[
                    {title:{[Op.like]:'%'+keyword+'%'}},
                    {content:{[Op.like]:'%'+keyword+'%'}},
                    {flag:{[Op.like]:'%'+keyword+'%'}}
                ]
            }
        });
        ctx.body={
            code:1000,
            data:row,
            msg:'查找指定数据成功'
        }
    }else{
        let row=await Blogs.findAll();
        ctx.body={
            code:1000,
            data:row,
            msg:'查找所有数据成功'
        }
    }
});

koa.use(bodyparser());
koa.use(cors());
koa.use(router.routes());

koa.listen(3000,()=>{
    console.log('服务器运行在http://localhost:3000上');
})